package com.zhsj.OkeHomeConsumption.ui.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.hjq.base.BaseDialog;
import com.hjq.dialog.MessageDialog;
import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyLazyFragment;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.ui.activity.HomeActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.IndexCityList;
import com.zhsj.OkeHomeConsumption.ui.activity.InvitePActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.LoginActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.RetrunActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.WebActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.WebUserActivity;
import com.zhsj.OkeHomeConsumption.ui.fragment.integral.activity.IntegralActivity;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bingoogolapple.bgabanner.BGABanner;

import static com.zhsj.OkeHomeConsumption.common.Constants.SHARED_PERFERENCE_USERINFO;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 赚积分
 */
public final class TestFragmentD extends MyLazyFragment<HomeActivity> {

    @BindView(R.id.yaoqingkehu_lin)
    LinearLayout yaoqingkehuLin;
    @BindView(R.id.yaoqinghaoyou_lin)
    LinearLayout yaoqinghaoyouLin;
    Unbinder unbinder;
    /**
     * @Fields mSharedPreferanceUtils : TODO
     */
    private SharedPreferanceUtils mSharePreferanceUtils = null;

    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private BaseDialog pDialogUtils = null;
    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;
    private BGABanner bannerGuideContent;
    /**
     * @Fields topurlArr : TODO banner部url标题集合
     */
    private LinkedHashMap<String, String> topUrlTitleArr = null;
    //图片集合
    private ArrayList<String> imageUrlList = null;
    private ArrayList<String> webUrlList = null;
    private ArrayList<Integer> imagemodle = null;
    private List<String> mBannerTitleLists = null;
    public static TestFragmentD newInstance() {
        return new TestFragmentD();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_test_d;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_test_d_title;
    }

    @Override
    protected void initView() {
        pDialogUtils = new BaseDialog(getActivity());
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        bannerGuideContent = findViewById(R.id.banner_guide_content);
    }

    @Override
    protected void initData() {

        mSharePreferanceUtils = new SharedPreferanceUtils(getActivity());
        PostCityName(8);
        bannerGuideContent.setDelegate(new BGABanner.Delegate<ImageView, String>() {
            @Override
            public void onBannerItemClick(BGABanner banner, ImageView itemView, String model, int position) {
                startActivity(new Intent(getActivity(), WebActivity.class).putExtra("url", webUrlList.get(position)));
//                Toast.makeText(banner.getContext(), "点击了" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.yaoqingkehu_lin, R.id.yaoqinghaoyou_lin, R.id.banner_image})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.yaoqingkehu_lin:
                //推荐家装客户
                if (mSharePreferanceUtils.getToken().equals("")) {
                    startActivity(LoginActivity.class);
                } else {
                    Intent intent = new Intent(getActivity(), SharedActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.yaoqinghaoyou_lin:
                //邀请会员
                if (mSharePreferanceUtils.getToken().equals("")) {
                    startActivity(LoginActivity.class);
                } else {
                    Intent intent2 = new Intent(getActivity(), InvitePActivity.class);
                    startActivity(intent2);
                }
                break;
            case R.id.banner_image:
                if (mSharePreferanceUtils.getToken().equals("")) {
                    startActivity(LoginActivity.class);
                } else {
                    Intent intent3 = new Intent(getActivity(), IntegralActivity.class);
                    startActivity(intent3);
                }

                break;
        }
    }
    /**
     * 获取定位城市的id
     */
    public void PostCityName(int name) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mArticleDiaryHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mArticleDiaryHashMap.put("v", Constants.APPVERSION);
        mArticleDiaryHashMap.put("t", Constants.TIME);
        mArticleDiaryHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mArticleDiaryHashMap.put("client", Constants.CLIENT);
        LogUtils.e("ArticleDiaryPost time =", Constants.TIME);
        mArticleDiaryHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mArticleDiaryHashMap.put("platform", Constants.PLAFORM);


        mArticleDiaryHashMap.put("mark", "10");
        paramMaps.put("mark","10");

        mArticleDiaryHashMap.put("module", String.valueOf(name));
        paramMaps.put("module",String.valueOf(name));
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mArticleDiaryHashMap);
        HttpClient.get(OkeHomeConsumptionApi.MONEY_LUNBOTU, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 首页Banner数据
                        JSONArray optJSONArray = jsonOBJ.optJSONArray("data");
                        topUrlTitleArr = new LinkedHashMap<String, String>();
                        imageUrlList = new ArrayList<String>();
                        webUrlList = new ArrayList<>();
                        imagemodle = new ArrayList<>();
                        mBannerTitleLists = new ArrayList<String>();
                        // 首页数据
                        for (int i = 0; i < optJSONArray.length(); i++) {
                            final JSONArray imgPathArray = optJSONArray.optJSONObject(i).optJSONArray("imgPath");
                            if (!imageUrlList.contains(imgPathArray.optString(0))) {
                                imageUrlList.add(imgPathArray.optString(0));
                            }
                            if (!topUrlTitleArr.containsKey(optJSONArray.optJSONObject(i).optString("title")) &&
                                    !topUrlTitleArr.containsValue(optJSONArray.optJSONObject(i).optString("url"))) {
                                topUrlTitleArr.put(optJSONArray.optJSONObject(i).optString("title"),
                                        optJSONArray.optJSONObject(i).optString("url"));
                                mBannerTitleLists.add(optJSONArray.optJSONObject(i).optString("title"));
                                imagemodle.add(optJSONArray.optJSONObject(i).optInt("module"));
                                webUrlList.add(optJSONArray.optJSONObject(i).optString("url"));
                            }

                        }
                        //设置图片集合
                        bannerGuideContent.setAdapter(new BGABanner.Adapter<ImageView, String>() {
                            @Override
                            public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                                Glide.with(getActivity())
                                        .load(model)
//                                .placeholder(R.drawable.homebanneryi)
                                        .error(R.drawable.homebannerer)
                                        .centerCrop()
                                        .dontAnimate()
                                        .into(itemView);
                            }
                        });

                        bannerGuideContent.setData(imageUrlList, mBannerTitleLists);
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        // token过期
                        if (!message.equals("null")) {
                        }
                    } else {
                        if (!message.equals("null")) {
                        }

                    }
                } catch (Exception ex) {
                    LogUtils.e("IndexFragemnt banner", "数据获取异常 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

}